package com.holyland.action;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.validation.SkipValidation;

import static com.holyland.util.IHolylandConstants.SESSION_USER;

import com.holyland.model.User;
import com.holyland.service.MemberService;
import com.holyland.util.HolylandException;

public class ChangePswdAction extends BaseAction {
	
	private static final long serialVersionUID = 5524227638002631475L;
	
	private String oldpswd;
	private String newpswd;
	private String newpswdconfirm;
	
	public String getOldpswd() {
		return oldpswd;
	}
	public void setOldpswd(String oldpswd) {
		this.oldpswd = oldpswd;
	}
	public String getNewpswd() {
		return newpswd;
	}
	public void setNewpswd(String newpswd) {
		this.newpswd = newpswd;
	}
	public String getNewpswdconfirm() {
		return newpswdconfirm;
	}
	public void setNewpswdconfirm(String newpswdconfirm) {
		this.newpswdconfirm = newpswdconfirm;
	}
	
	@SkipValidation
	public String showChangePassword() throws HolylandException {
		
		return FWD_SUCCESS;
	}
	
	public String changePassword() throws HolylandException {
		User user = (User) session.get(SESSION_USER);
		
		if(user != null) {
			user.setPassword(newpswd);
			user.setFirstTimeLogin(false);
			
			User edited = MemberService.getInstance().editUser(user);
			
			session.remove(SESSION_USER);			
			session.put(SESSION_USER, edited);
		}
		
		return FWD_SUCCESS;
	}
	@Override
	public void validate() {
		if(StringUtils.isBlank(oldpswd)) {
			addActionError(getText("errRequired", new String[]{"Kata Kunci Lama"}));
		}
		
		if(StringUtils.isBlank(newpswd)) {
			addActionError(getText("errRequired", new String[]{"Kata Kunci Baru"}));
		}
		
		if(StringUtils.isBlank(newpswdconfirm)) {
			addActionError(getText("errRequired", new String[]{"Konfimasi Kata Kunci Baru"}));
		}
		
		if(!StringUtils.equals(newpswd, newpswdconfirm)) {
			addActionError("Konfirmasi kata kunci baru tidak sesuai.");
		}
	}		

}
